#region

using System;
using System.Collections.Generic;
using DomainModel.Domain.Model.MessageTypeModel;
using DomainModel.Domain.Model.ServiceModel;
using DomainModel.Domain.Model.SubscriptionModel;
using DomainModel.Utils;
using NHibernate;
using NHibernate.Criterion;

#endregion

namespace DomainModel.Infrastructure.Persistence
{
    public class SubscriptionsRepository : BaseRepository<Subscription, SubscriptionId>, ISubscriptionsRepository
    {
        public SubscriptionsRepository(ISession session, IApplicationConfig applicationConfig)
            : base(session, applicationConfig)
        {
        }

        public Subscription Get(MessageType messageType, Service publisher, Service subscriber)
        {

            var subscription = BuildCriteria()
                .Add(Restrictions.Eq("MessageType", messageType))
                .Add(Restrictions.Eq("Publisher", publisher))
                .Add(Restrictions.Eq("Subscriber", subscriber))
                .UniqueResult<Subscription>();

            return subscription;
        }

        public IList<MessageType> GetMessageTypesExposedByPublisher(Service publisher)
        {
            var messageTypes = BuildCriteria()
                .SetProjection(Projections.Property("MessageType"))
                .Add(Restrictions.Eq("Publisher", publisher))
                .List<MessageType>();

            return messageTypes;
        }

        public IList<Subscription> GetBySubscriber(Service subscriber)
        {
            var subscriptions = BuildCriteria()
                .Add(Restrictions.Eq("Subscriber", subscriber))
                .List<Subscription>();

            return subscriptions;
        }

        public IList<Subscription> GetByPublisher(Service publisher)
        {
            var subscriptions = BuildCriteria()
                .Add(Restrictions.Eq("Publisher", publisher))
                .List<Subscription>();

            return subscriptions;
        }

        public SubscriptionId NextSubscriptionId()
        {
            return new SubscriptionId(NextIntFromSeq());
        }
    }
}